package com.example.play_car

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.VideoView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.play_car.databinding.ItemPostBinding

/**
 * 帖子列表适配器，支持多图九宫格
 */
class PostAdapter : RecyclerView.Adapter<PostAdapter.VH>() {
    private val data = mutableListOf<Post>()
    val currentList: List<Post> get() = data

    fun submitList(list: List<Post>) {
        data.clear()
        data.addAll(list)
        notifyDataSetChanged()
    }

    class VH(val binding: ItemPostBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        return VH(ItemPostBinding.inflate(LayoutInflater.from(parent.context), parent, false))
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        val post = data[position]
        holder.binding.tvNickname.text = post.nickname
        holder.binding.tvContent.text = post.content
        holder.binding.tvLike.text = post.likeCount?.toString() ?: "0"
        holder.binding.tvComment.text = post.commentCount?.toString() ?: "0"
        // 加载头像
        Glide.with(holder.itemView.context)
            .load(post.avatar)
            .placeholder(com.example.common_pic.R.drawable.headimg)
            .transform(CenterCrop(),CircleCrop())
            .into(holder.binding.ivAvatar)
        // 图片九宫格
        holder.binding.rvImages.layoutManager = GridLayoutManager(holder.itemView.context, 3)
        val images = post.images ?: emptyList()
        holder.binding.rvImages.adapter = ImageGridAdapter(images)
        holder.binding.rvImages.isNestedScrollingEnabled = false
    }

    override fun getItemCount() = data.size
}

/**
 * 图片九宫格适配器
 */
class ImageGridAdapter(private val images: List<String>) : RecyclerView.Adapter<ImageGridAdapter.VH>() {
    class VH(val view: View) : RecyclerView.ViewHolder(view) {
        val image: ImageView = view.findViewById(R.id.image)
        val playIcon: ImageView = view.findViewById(R.id.playIcon)
        val videoView: VideoView = view.findViewById(R.id.videoView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_grid_media, parent, false)
        val displayMetrics = parent.resources.displayMetrics
        val density = displayMetrics.density

        val params = if (images.size == 1) {
            // 单图大图，宽度撑满父布局，高度按比例（如16:9）
            val width = parent.measuredWidth.takeIf { it > 0 } ?: displayMetrics.widthPixels
            val padding = (12 * density).toInt() * 2 // 与item_post.xml一致
            val realWidth = width - padding
            RecyclerView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                (realWidth * 9 / 16) // 16:9比例
            ).apply {
                setMargins((4 * density).toInt(), (4 * density).toInt(), (4 * density).toInt(), (4 * density).toInt())
            }
        } else {
            // 九宫格
            val padding = (12 * density).toInt() * 2
            val space = (8 * density).toInt() * 2
            val spanCount = 3
            val size = (displayMetrics.widthPixels - padding - space) / spanCount
            RecyclerView.LayoutParams(size, size).apply {
                setMargins((4 * density).toInt(), (4 * density).toInt(), 0, 0)
            }
        }
        view.layoutParams = params
        return VH(view)
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        val url = images[position]
        val isVideo = url.contains(".mp4") // 或用contentType判断

        holder.videoView.visibility = View.GONE
        holder.image.visibility = View.VISIBLE
        holder.playIcon.visibility = if (isVideo) View.VISIBLE else View.GONE

        Glide.with(holder.image.context)
            .load(url)
            .centerCrop()
            .into(holder.image)

        if (isVideo) {
            holder.image.setOnClickListener {
                holder.image.visibility = View.GONE
                holder.playIcon.visibility = View.GONE
                holder.videoView.visibility = View.VISIBLE
                holder.videoView.setVideoPath(url)
                holder.videoView.start()
                holder.videoView.setOnCompletionListener {
                    holder.videoView.visibility = View.GONE
                    holder.image.visibility = View.VISIBLE
                    holder.playIcon.visibility = View.VISIBLE
                }
            }
        } else {
            holder.image.setOnClickListener(null)
        }
    }

    override fun getItemCount() = images.size
}